<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="userId" label="用户ID">
          <el-input v-model="searchData.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item prop="userType" label="用户类型">
          <el-select v-model="searchData.userType" placeholder="请选择" clearable style="width: 120px;">
            <el-option label="顾客" :value="1" />
            <el-option label="商户" :value="2" />
            <el-option label="配送员" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item prop="typeId" label="反馈类型">
          <el-select v-model="searchData.typeId" placeholder="请选择" clearable style="width: 150px;">
            <el-option
              v-for="item in feedbackTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-select v-model="searchData.status" placeholder="请选择" clearable style="width: 120px;">
            <el-option label="未处理" :value="0" />
            <el-option label="已处理" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item prop="contact" label="联系方式">
          <el-input v-model="searchData.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="RefreshRight" @click="getFeedbackData">刷新数据</el-button>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="feedbackData">
          <el-table-column type="index" width="80" align="center" label="序号" :index="indexMethod" />
          <el-table-column prop="userId" label="用户ID" align="center" width="100" />
          <el-table-column prop="userTypeName" label="用户类型" align="center" width="100">
            <template #default="scope">
              <el-tag :type="getUserTypeTagType(scope.row.userType)">{{ scope.row.userTypeName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="typeName" label="反馈类型" align="center" width="120" />
          <el-table-column prop="content" label="反馈内容" align="center" show-overflow-tooltip width="200" />
          <el-table-column prop="images" label="图片" align="center" width="100">
            <template #default="scope">
              <el-button v-if="scope.row.images" type="text" size="small" @click="viewImages(scope.row.images)">
                查看图片
              </el-button>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="contact" label="联系方式" align="center" width="120" />
          <el-table-column prop="statusName" label="状态" align="center" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">{{ scope.row.statusName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="handleRemark" label="处理备注" align="center" show-overflow-tooltip width="150" />
          <el-table-column prop="handelTime" label="处理时间" align="center" width="160" />
          <el-table-column prop="createTime" label="创建时间" align="center" width="160" />
          <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="viewDetail(scope.row)">查看详情</el-button>
              <el-button
                v-if="scope.row.status === 0"
                type="success"
                text
                bg
                size="small"
                @click="handleFeedback(scope.row)"
              >
                处理
              </el-button>
              <el-button type="danger" text bg size="small" @click="deleteFeedback(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 反馈详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="反馈详情" width="600px">
      <div v-if="currentFeedback">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ currentFeedback.userId }}</el-descriptions-item>
          <el-descriptions-item label="用户类型">{{ currentFeedback.userTypeName }}</el-descriptions-item>
          <el-descriptions-item label="反馈类型">{{ currentFeedback.typeName }}</el-descriptions-item>
          <el-descriptions-item label="联系方式">{{ currentFeedback.contact }}</el-descriptions-item>
          <el-descriptions-item label="状态" :span="2">
            <el-tag :type="currentFeedback.status === 1 ? 'success' : 'warning'">{{ currentFeedback.statusName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="反馈内容" :span="2">
            <div style="white-space: pre-wrap;">{{ currentFeedback.content }}</div>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentFeedback.images" label="图片" :span="2">
            <div class="image-list">
              <el-image
                v-for="(image, index) in getImageList(currentFeedback.images)"
                :key="index"
                :src="image"
                :preview-src-list="getImageList(currentFeedback.images)"
                :initial-index="index"
                style="width: 100px; height: 100px; margin-right: 10px;"
                fit="cover"
              />
            </div>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentFeedback.handleRemark" label="处理备注" :span="2">
            <div style="white-space: pre-wrap;">{{ currentFeedback.handleRemark }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="处理时间">{{ currentFeedback.handelTime || '未处理' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentFeedback.createTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 处理反馈对话框 -->
    <el-dialog v-model="handleDialogVisible" title="处理反馈" width="500px">
      <el-form ref="handleFormRef" :model="handleFormData" :rules="handleFormRules" label-width="100px">
        <el-form-item label="处理备注" prop="handleRemark">
          <el-input
            v-model="handleFormData.handleRemark"
            type="textarea"
            :rows="4"
            placeholder="请输入处理备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmHandle">确认处理</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="imageDialogVisible" title="图片预览" width="800px">
      <div class="image-preview">
        <el-image
          v-for="(image, index) in previewImages"
          :key="index"
          :src="image"
          :preview-src-list="previewImages"
          :initial-index="index"
          style="width: 150px; height: 150px; margin: 10px;"
          fit="cover"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from "vue"
import {
  getFeedbackListApi,
  getFeedbackDetailApi,
  handleFeedbackApi,
  deleteFeedbackApi,
  getEnabledFeedbackTypesApi
} from "@/api/feedback-manage"
import { type FeedbackData } from "@/api/feedback-manage/types/feedback"
import { type FeedbackTypeData } from "@/api/feedback-manage/types/feedback-type"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"

defineOptions({
  name: "FeedbackManage"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 查询
const feedbackData = ref<FeedbackData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  userId: undefined as number | undefined,
  userType: undefined as number | undefined,
  typeId: undefined as number | undefined,
  status: undefined as number | undefined,
  contact: ""
})

// 反馈类型选项
const feedbackTypeOptions = ref<FeedbackTypeData[]>([])

const getFeedbackData = () => {
  loading.value = true
  getFeedbackListApi({
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    userId: searchData.userId || undefined,
    userType: searchData.userType || undefined,
    typeId: searchData.typeId || undefined,
    status: searchData.status,
    contact: searchData.contact || undefined
  })
    .then(({ data }) => {
      paginationData.total = data.total
      feedbackData.value = data.list
    })
    .catch(() => {
      feedbackData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  paginationData.currentPage = 1
  getFeedbackData()
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

// 获取反馈类型选项
const getFeedbackTypeOptions = () => {
  getEnabledFeedbackTypesApi()
    .then(({ data }) => {
      feedbackTypeOptions.value = data
    })
    .catch(() => {
      feedbackTypeOptions.value = []
    })
}

//#region 详情
const detailDialogVisible = ref<boolean>(false)
const currentFeedback = ref<FeedbackData | null>(null)

const viewDetail = (row: FeedbackData) => {
  currentFeedback.value = row
  detailDialogVisible.value = true
}

//#region 处理反馈
const handleDialogVisible = ref<boolean>(false)
const handleFormRef = ref<FormInstance | null>(null)
const handleFormData = reactive({
  feedbackId: 0,
  handleRemark: ""
})

const handleFormRules: FormRules = {
  handleRemark: [{ required: true, trigger: "blur", message: "请输入处理备注" }]
}

const handleFeedback = (row: FeedbackData) => {
  handleFormData.feedbackId = row.id
  handleFormData.handleRemark = ""
  handleDialogVisible.value = true
}

const confirmHandle = () => {
  handleFormRef.value?.validate((valid: boolean) => {
    if (!valid) return
    loading.value = true
    handleFeedbackApi(handleFormData)
      .then(() => {
        ElMessage.success("处理成功")
        handleDialogVisible.value = false
        getFeedbackData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

//#region 删除
const deleteFeedback = (row: FeedbackData) => {
  ElMessageBox.confirm(`确认删除反馈"${row.content.substring(0, 20)}..."?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteFeedbackApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getFeedbackData()
    })
  })
}

//#region 图片预览
const imageDialogVisible = ref<boolean>(false)
const previewImages = ref<string[]>([])

const viewImages = (images: string) => {
  previewImages.value = getImageList(images)
  imageDialogVisible.value = true
}

const getImageList = (images: string): string[] => {
  if (!images) return []
  return images.split(",").filter(img => img.trim())
}

//#region 工具函数
const getUserTypeTagType = (userType: number) => {
  switch (userType) {
    case 1:
      return "success"
    case 2:
      return "warning"
    case 3:
      return "info"
    default:
      return "info"
  }
}

const indexMethod = (index: number) => {
  return index + 1 + (paginationData.currentPage - 1) * paginationData.pageSize
}

//#region 监听分页参数变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getFeedbackData, { immediate: true })

//#region 初始化
onMounted(() => {
  getFeedbackTypeOptions()
})
</script>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
}

.image-preview {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
</style>